package com.zjhb.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.zjhb.common.controller.ExcelUtil;
import com.zjhb.common.controller.ExportBean;
import com.zjhb.common.dao.BaseDao;
import com.zjhb.common.dao.Page;
import com.zjhb.common.enumutil.Area;
import com.zjhb.common.enumutil.Remark;
import com.zjhb.common.enumutil.UserTypes;
import com.zjhb.common.enumutil.Verify;
import com.zjhb.common.util.DateUtil;
import com.zjhb.common.util.ResourceUtil;
import com.zjhb.common.util.ResponseUtil;
import com.zjhb.common.util.StringMyUtil;
import com.zjhb.dto.KeepDTO;
import com.zjhb.entity.AssetsEntity;
import com.zjhb.entity.DepartmentEntity;
import com.zjhb.entity.FileEntity;
import com.zjhb.entity.KeepApplyEntity;
import com.zjhb.entity.KeepInfoEntity;
import com.zjhb.entity.UserEntity;

import param.KeepParam;
import param.UserParam;
import param.VerifyParam;

@RestController
@RequestMapping("/keep")
public class KeepController {
	@Autowired
	BaseDao baseDao;

	@PostMapping("/add")
	public JSONObject apply(KeepApplyEntity keepApply) throws Exception {
		JSONObject j = new JSONObject();
		if (StringMyUtil.isNotEmpty(keepApply.getNumber())) {
			Criteria crt = baseDao.getCriteria(AssetsEntity.class);
			crt.add(Restrictions.eq("code", keepApply.getNumber()));
			AssetsEntity assetsEntity = (AssetsEntity) crt.uniqueResult();
			if (assetsEntity == null) {
				j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "物品编号错误", "");
				return j;
			}
			keepApply.setAreaId(assetsEntity.getAreaId());
			keepApply.setDepartId(assetsEntity.getDepartId());
			keepApply.setDepartIdName(assetsEntity.getDepartName());
			keepApply.setName(assetsEntity.getName());
			keepApply.setAssetsId(assetsEntity.getId());
			keepApply.setCodeUrl(assetsEntity.getCodeUrl());
		} else {
			if (ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
				if (StringMyUtil.isEmpty(keepApply.getDepartId())) {
					j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "部门 is null", "");
					return j;
				}
				DepartmentEntity depart = baseDao.getById(DepartmentEntity.class, keepApply.getDepartId());
				if (depart == null) {
					j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, " depart is null", "");
					return j;
				}
				keepApply.setDepartIdName(depart.getName());
			} else {
				DepartmentEntity depart = baseDao.getById(DepartmentEntity.class,
						ResourceUtil.getCurrentUser().getDepartId());
				if (depart == null) {
					j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, " depart is null", "");
					return j;
				}
				keepApply.setDepartId(ResourceUtil.getCurrentUser().getDepartId());
				keepApply.setDepartIdName(depart.getName());
			}
			if (StringMyUtil.isEmpty(keepApply.getName()) || StringMyUtil.isEmpty(keepApply.getAreaId())) {
				j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "name area is null", "");
				return j;
			}

		}
		keepApply.setCreateTime(ResourceUtil.getNowTime());
		keepApply.setCreateUser(ResourceUtil.getCurrentUser().getId());
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.between("createTime", ResourceUtil.getTime(DateUtil.beginOfDate(new Date())),
				ResourceUtil.getTime(DateUtil.endOfDate(new Date()))));
		keepApply.setStatus(Verify.WaitVerify.getKey());
		if (ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			if (StringMyUtil.isEmpty(keepApply.getKeepUserId())) {
				j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "请选择维修人员", "");
				return j;
			}
			keepApply.setStatus(Verify.WaitKeep.getKey());
		}
		Long totalNum = baseDao.getCount(crt);
		keepApply.setCode(ResourceUtil.getStringNowYnd() + (totalNum + 1));
		baseDao.save(keepApply);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	// 添加维修动态
	@PostMapping("/info/add")
	public JSONObject addInfo(KeepInfoEntity param) {
		if (!ResourceUtil.isAdminOrLeader()) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		baseDao.save(param);
		return ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
	}

	// 维修申请 维修
	// 待审核列表
	@PostMapping("/apply/verify")
	public JSONObject applyVerify(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.eq("status", Verify.WaitVerify.getKey()));
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		return buildList(param, crt, resp);
	}

	// 维修申请 维修
	// 拒绝列表
	@PostMapping("/apply/refuse")
	public JSONObject applyRefuse(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.or(Restrictions.eq("status", Verify.RefuseVerify.getKey()),
				Restrictions.eq("status", Verify.RefuseKeep.getKey())));
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		return buildList(param, crt, resp);
	}

	// 待审核列表
	@PostMapping("/admin/verify")
	public JSONObject waitVerify(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.eq("status", Verify.WaitVerify.getKey()));
		return buildList(param, crt, resp);
	}

	// 拒绝列表
	@PostMapping("/admin/refuse")
	public JSONObject refuse(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.or(Restrictions.eq("status", Verify.RefuseVerify.getKey()),
				Restrictions.eq("status", Verify.RefuseKeep.getKey())));
		return buildList(param, crt, resp);
	}

	// 维修进度
	@PostMapping("/speed/keeping")
	public JSONObject speedKeep(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		crt.add(Restrictions.eq("status", Verify.WaitKeep.getKey()));
		return buildList(param, crt, resp);
	}

	// 维修进度
	// 已完成
	@PostMapping("/speed/finish")
	public JSONObject speedFinish(KeepParam param, HttpServletResponse resp) throws Exception {
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		crt.add(Restrictions.eq("status", Verify.Finish.getKey()));
		return buildList(param, crt, resp);
	}

	// 审核
	@PostMapping("/verify")
	public JSONObject verify(VerifyParam param) throws Exception {
		JSONObject j = new JSONObject();
		KeepApplyEntity bean = baseDao.getById(KeepApplyEntity.class, param.getId());
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "请联系管理员", "");
			return j;
		}
		if (param.getCode().equals("1")) {
			if (bean.getStatus().equals(Verify.WaitVerify.getKey())) {
				if (StringMyUtil.isEmpty(param.getKeepUserId())) {
					j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "请选择维修人员", "");
					return j;
				}
				bean.setStatus(Verify.WaitKeep.getKey());
				bean.setVerifyTime(ResourceUtil.getNowTime());
				bean.setKeepUserId(param.getKeepUserId());
			} else {
				bean.setKeepTime(ResourceUtil.getNowTime());
				bean.setStatus(Verify.Finish.getKey());
			}
			baseDao.update(bean);
		} else if (param.getCode().equals("0")) {
			if (bean.getStatus().equals(Verify.WaitVerify.getKey())) {
				bean.setStatus(Verify.RefuseVerify.getKey());
				bean.setVerifyTime(ResourceUtil.getNowTime());
			} else if (bean.getStatus().equals(Verify.WaitKeep.getKey())) {
				bean.setStatus(Verify.RefuseKeep.getKey());
				bean.setKeepTime(ResourceUtil.getNowTime());
			}
			bean.setReason(param.getReason());
			baseDao.update(bean);
		} else {
			j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "参数不对", "");
			return j;
		}
		baseDao.update(bean);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	// 评论
	@PostMapping("/remark")
	public JSONObject remark(KeepApplyEntity keepApply) throws Exception {
		JSONObject j = new JSONObject();
		KeepApplyEntity bean = baseDao.getById(KeepApplyEntity.class, keepApply.getId());
		if (StringMyUtil.isNotEmpty(bean.getRemark())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "已经评论过", "");
			return j;
		}
		if (!bean.getStatus().equals(Verify.Finish.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "改项目目前还没有完成维修", "");
			return j;
		}
		bean.setRemark(keepApply.getRemark());
		bean.setRemarkInfo(keepApply.getRemarkInfo());
		baseDao.update(bean);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	private JSONObject buildList(KeepParam param, Criteria crt, HttpServletResponse resp) throws Exception {
		JSONObject j = new JSONObject();
		Page<KeepApplyEntity> page = new Page<>();
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			if (!ResourceUtil.isAdminOrLeader()) {
				j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您不能选择部门", "");
				return j;
			}
			crt.add(Restrictions.eq("departId", param.getDepatmentId()));
		}
		if (StringMyUtil.isNotEmpty(param.getStartDate()) && StringMyUtil.isNotEmpty(param.getEndDate())) {
			crt.add(Restrictions.between("createTime", 
					ResourceUtil.getJsonTime(param.getStartDate()),ResourceUtil.getJsonTime(param.getEndDate())));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getCode())) {
			crt.add(Restrictions.like("code", param.getCode(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getQrCode())) {
			crt.add(Restrictions.like("number", param.getQrCode(), MatchMode.ANYWHERE));
		}
		crt.setMaxResults(param.getLimit());
		crt.setFirstResult(param.getOffset());
		crt.addOrder(Order.desc("createTime"));
		List<KeepApplyEntity> list = crt.list();
		if (list.size() > 0) {
			for (KeepApplyEntity keep : list) {
				keep.setAreaDesc(Area.parse(keep.getAreaId()).getValue());
				keep.setStatusDesc(Verify.parse(keep.getStatus()).getValue());
				if (StringMyUtil.isNotEmpty(keep.getRemark())) {
					keep.setRemarkDesc(Remark.parse(keep.getRemark()).getValue());
				}
			}
		}
		Long totalNum = baseDao.getCount(crt);
		page.setRows(list);
		page.setTotal(totalNum);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", page);
		return j;
	}

	// 维修申请 维修
	// 待审核列表
	@PostMapping("/verify/down")
	public void verifydown(KeepParam param, HttpServletResponse resp, HttpServletRequest request) throws Exception {
		if (!ResourceUtil.validate(request)) {
			return;
		}
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.eq("status", Verify.WaitVerify.getKey()));
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		down(param,  crt,  resp,  request);
	}

	// 维修申请 维修
	// 拒绝列表
	@PostMapping("/refuse/down")
	public void refusedown(KeepParam param, HttpServletResponse resp, HttpServletRequest request) throws Exception {
		if (!ResourceUtil.validate(request)) {
			return;
		}
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.or(Restrictions.eq("status", Verify.RefuseVerify.getKey()),
				Restrictions.eq("status", Verify.RefuseKeep.getKey())));
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		down(param,  crt,  resp,  request);
	}

	// 待审核列表
	@PostMapping("/keeping/down")
	public void keepdown(KeepParam param, HttpServletResponse resp, HttpServletRequest request) throws Exception {
		if (!ResourceUtil.validate(request)) {
			return;
		}
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		crt.add(Restrictions.eq("status", Verify.WaitKeep.getKey()));
		down(param,  crt,  resp,  request);
	}

	// 维修进度
	// 已完成
	@PostMapping("/finish/down")
	public void finishdown(KeepParam param, HttpServletResponse resp, HttpServletRequest request) throws Exception {
		if (!ResourceUtil.validate(request)) {
			return;
		}
		Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
		if (!ResourceUtil.isAdminOrLeader()) {
			crt.add(Restrictions.eq("departId", ResourceUtil.getCurrentUser().getDepartId()));
		}
		crt.add(Restrictions.eq("status", Verify.Finish.getKey()));
		down(param,  crt,  resp,  request);
		
	}

	public void down(KeepParam param, Criteria crt, HttpServletResponse resp, HttpServletRequest request)
			throws Exception {
		// 语言选择
		
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			if (!ResourceUtil.isAdminOrLeader()) {				
				return ;
			}
			crt.add(Restrictions.eq("departId", param.getDepatmentId()));
		}
		if (StringMyUtil.isNotEmpty(param.getStartDate()) && StringMyUtil.isNotEmpty(param.getEndDate())) {
			crt.add(Restrictions.between("createTime", 
					ResourceUtil.getJsonTime(param.getStartDate()),ResourceUtil.getJsonTime(param.getEndDate())));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getCode())) {
			crt.add(Restrictions.like("code", param.getCode(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getQrCode())) {
			crt.add(Restrictions.like("number", param.getQrCode(), MatchMode.ANYWHERE));
		}
		List<KeepApplyEntity> list = crt.list();
		if (list.size() > 0) {
			for (KeepApplyEntity keep : list) {
				keep.setAreaDesc(Area.parse(keep.getAreaId()).getValue());
				if (StringMyUtil.isNotEmpty(keep.getRemark())) {
					keep.setRemarkDesc(Remark.parse(keep.getRemark()).getValue());
				}
			}
		}
		ExportBean<KeepApplyEntity> bean = new ExportBean<>();
		bean.setPoList(list);
		bean.setHeader(new String[] { "单号", "时间", "名称", "申报部门", "区域", "位置", "联系人", "电话", "驳回原因", "具体描述","满意度",
				"具体评论","维修人"});
		
		bean.setHeaderSize(13);
		bean.setTitle("维修");
		resp.setHeader("Content-Disposition",
				"attachment;filename=" + new String("维修.xls".getBytes("gb2312"), "ISO8859-1"));
		ExcelUtil.exportFromBean(bean, resp.getOutputStream());
		
	}

	@PostMapping("/user/select")
	public JSONObject userList(UserParam param) {
		// 语言选择
		JSONObject j = new JSONObject();
		Criteria crt = baseDao.getCriteria(UserEntity.class);
		crt.add(Restrictions.eq("status", "1")).add(Restrictions.eq("types", UserTypes.Keep.getKey()));
		List<UserEntity> list = crt.list();
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", list);
		return j;
		// 默认菜单

	}

	@PostMapping("/delete/{id}")
	public JSONObject delete(HttpServletRequest req, @PathVariable String id) {
		JSONObject j = new JSONObject();
		KeepApplyEntity keep = baseDao.getById(KeepApplyEntity.class, id);
		if (!(keep.getStatus().equals(Verify.RefuseKeep.getKey())
				|| keep.getStatus().equals(Verify.RefuseVerify.getKey()))) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		baseDao.delete(keep);
		baseDao.editNumHql("delete from " + KeepInfoEntity.class.getName() + " where keepApplyId=?",
				new Object[] { id });
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	// 具体信息

	@PostMapping("/find/{id}")
	public JSONObject find(HttpServletRequest req, @PathVariable String id) {
		JSONObject j = new JSONObject();
		KeepDTO keepDTO = new KeepDTO();
		KeepApplyEntity keep = baseDao.getById(KeepApplyEntity.class, id);
		keep.setAreaDesc(Area.parse(keep.getAreaId()).getValue());
		keep.setStatusDesc(Verify.parse(keep.getStatus()).getValue());
		keep.setWaitRemark("待评论");
		if (StringMyUtil.isNotEmpty(keep.getRemark())) {
			keep.setRemarkDesc(Remark.parse(keep.getRemark()).getValue());
			keep.setWaitRemark("已评论");
		}
		List<String> history = new ArrayList<>();
		if (StringMyUtil.isNotEmpty(keep.getAssetsId())) {
			Criteria crt = baseDao.getCriteria(KeepApplyEntity.class);
			crt.add(Restrictions.eq("assetsId", keep.getAssetsId()));
			List<KeepApplyEntity> list = crt.list();
			if (list.size() > 1) {
				for (KeepApplyEntity keepApplyEntity : list) {
					if (!keepApplyEntity.getId().equals(keep.getId())) {
						String userName = baseDao.getById(UserEntity.class, keepApplyEntity.getCreateUser())
								.getRealName();
						String time = StringMyUtil.YearSplit(keep.getCreateTime());
						history.add(userName + "在" + time + "提交了一次维修申请");
					}
				}
			}

		}
		Criteria crtInfo = baseDao.getCriteria(KeepInfoEntity.class);
		crtInfo.add(Restrictions.eq("keepApplyId", id));
		crtInfo.addOrder(Order.desc("keepTime"));
		List<KeepInfoEntity> listkeepInfo = crtInfo.list();
		if (listkeepInfo.size() > 0) {
			String keepUserName = baseDao.getById(UserEntity.class, keep.getKeepUserId()).getRealName();
			for (KeepInfoEntity keepInfoEntity : listkeepInfo) {
				keepInfoEntity.setKeepUser(keepUserName);
				keepInfoEntity.setKeepUser(keep.getKeepUserId());
				Criteria crtFile = baseDao.getCriteria(FileEntity.class);
				crtFile.add(Restrictions.eq("tableName", keepInfoEntity.getId()));
				List<FileEntity> listFile = crtFile.list();
				keepInfoEntity.setFiles(listFile);
			}
		}
		keepDTO.setInfo(keep.getInfo());
		keepDTO.setKeep(keep);
		keepDTO.setHistory(history);
		keepDTO.setDongtai(listkeepInfo);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", keepDTO);
		return j;
	}
	public static void main(String[] args) {
		BigDecimal big =new BigDecimal(10);
		big=big.add(new BigDecimal(10));
		System.out.println(big);
	}

}
